import io.StdIn._
import java.io.PrintWriter
import scala.io.Source
object Main {
  def main(args: Array[String]): Unit = {
    println("Hello world!")
    //    readTest()
    //    printTest()
    //    writeFile()
    //    readFile()
    val x = -6
    val res = if (x > 0) 8 else -12
    println(s"res=$res")

//    whileTest()
    forTest()
  }

  def readTest(): Unit = {
    var i = readInt()
    println(s"i=$i")
    var f = readFloat()
    println(s"f=$f")
    var b = readBoolean()
    println(s"b=$b")
    var s = readLine("plead input your name:")
    println(s"s=$s")
  }

  def printTest(): Unit = {
    val i = 10
    val f = 3.1415
    val s = "hello"
    println(s"$s:i=$i,f=$f")
    println(f"$s:i=$i%-4d, f=$f%.1f")
  }

  def writeFile(): Unit = {
    // 写文件
    val outputFile=new PrintWriter("test.txt")
    outputFile.println("Today is Friday")
    outputFile.print("Spark is good")
    outputFile.close()
  }

  def readFile(): Unit = {
    val inputFile = Source.fromFile("inputfile.txt")
    val lines = inputFile.getLines()
    for (line <- lines)
      println(line)
    inputFile.close()
  }

  def whileTest(): Unit = {
    var end = 0
    while(end != -1) {
      println("请输入一个整数(输入-1表示结束):")
      end = readInt()
      println(s"你输入了数字: $end")
    }
    println("循环结束")
  }

  def forTest(): Unit = {
    for (i <- 1 to 3) {
      println(i)
    }


    for (i <- 10 until 15) {
      println(i)
    }

    for (i <- Array(4,5,6)) {
      println(i)
    }

    println("打印偶数----")
    for (i <- 1 to 5 if i % 2 ==0) {
      println(i)
    }

    for (i <- 2000 to 2024 if i % 4 == 0; if i % 100 != 0) {
      println(s"$i 是闰年")
    }

    for (i <- 1 to 5 if i%2==0; j <- 1 to 3 if j%2!=0) {
      println(i*j)
      // i: [2,4], j: [1, 3]
      // i=2, j[1, 3] ==> 2, 6
      // i=4, j[1,3] ==> 4, 12
    }

    // 每次执行时创造一个值，然后将包含所有产生值的容器对象作为for语句的结果返回。
    // for 的推导式：yield
    val r = for (i <- Array(1,2,3,4,5) if i % 2 == 0) yield {
      println(i)
      i
    }
    println(r.mkString(","))
  }
}